package com.originskyseed.platform.pk.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.pk.mapper.PkMapper;
import com.originskyseed.platform.pk.model.Pk;
import com.originskyseed.platform.pk.service.IPkService;
import com.originskyseed.platform.recruit.mapper.RecruitRelateRecommendMapper;
import com.originskyseed.platform.user.mapper.AnchorRelateLiveMapper;
import com.originskyseed.platform.user.mapper.DeptMapper;
import com.originskyseed.platform.user.mapper.PlayerMapper;
import com.originskyseed.platform.user.mapper.UserInfoMapper;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * pk信息表Service接口实现类（OSI_PK）
 *
 * @author WuZhuoXi
 */
@DubboService
@Component("pkService")
public class PkServiceImpl implements IPkService {

    @Resource
    private PkMapper pkMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private AnchorRelateLiveMapper anchorRelateLiveMapper;

    @Resource
    private PlayerMapper playerMapper;

    @Resource
    private RecruitRelateRecommendMapper recruitRelateRecommendMapper;

    /**
     * 删除记录
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByPrimaryKey(String id) throws Exception {
        return this.pkMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除记录
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByPrimaryKeys(List<String> ids) throws Exception {
        return this.pkMapper.deleteByPrimaryKeys(ids);
    }

    /**
     * 插入记录
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int insert(Pk record) throws Exception {
        if (StringUtils.isBlank(record.getId())) {
            record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
        }
        record.setCreateTime(new Date());
        return this.pkMapper.insert(record);
    }

    /**
     * 插入记录（仅非空值字段）
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int insertSelective(Pk record) throws Exception {
        if (StringUtils.isBlank(record.getId())) {
            record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
        }
        record.setCreateTime(new Date());
        return this.pkMapper.insertSelective(record);
    }

    /**
     * 更新记录
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKey(Pk record) throws Exception {
        record.setUpdateTime(new Date());
        return this.pkMapper.updateByPrimaryKey(record);
    }

    /**
     * 更新记录（仅非空值字段）
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKeySelective(Pk record) throws Exception {
        record.setUpdateTime(new Date());
        return this.pkMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 更新记录（租户模式）
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKeySelectiveTenantCode(Pk record, String tenantCode) throws Exception {
        if (StringUtils.isNotEmpty(tenantCode)) {
            TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
        }
        return this.updateByPrimaryKey(record);
    }

    /**
     * pk结果更新
     *
     * @param id
     * @param objUserId
     * @param result
     * @return
     * @throws Exception
     */
    @Override
    public int updateByIdAndObjUserIdStatePrimaryKey(String id, String objUserId, Integer result) throws Exception {
        return this.pkMapper.updateByIdAndObjUserIdStatePrimaryKey(id, objUserId, result);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Pk selectByPrimaryKey(String id) throws Exception {
        return this.pkMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询列表
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public List<Pk> selectList(Pk record) throws Exception {
        return this.pkMapper.selectList(record);
    }

    /**
     * 分页查询列表
     *
     * @param params
     * @param page
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Pk> selectListByPage(Map<String, Object> params, BasePage<Pk> page, UserInfo userInfo) throws Exception {
        params.put("page", page);
        List<Pk> list = new ArrayList<>();
        if(userInfo.getSourceSys() != 0) {
            /*int userInfoType = userInfo.getType();
            if (userInfoType == 6 || userInfoType == 11) {
                params.put("loginUser", userInfo.getId());//移除我的pk数据
            } else {
                params.put("loginUser", userInfo.getDeptId());
            }*/
            list = this.pkMapper.selectListByPage(params);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Pk pk = list.get(i);
                    int type = pk.getObjUserType();
                    String objId = "";
                    String toUserId = "";
                    if (pk.getObjUserId() != null && pk.getToUserId() != null) {
                        if (type == 6 || type == 11) {
                            objId = pk.getObjUserId();
                            toUserId = pk.getToUserId();
                            UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(pk.getObjUserId());
                            if (userInfo1 != null && userInfo1.getHeadPortrait() != null) {
                                pk.setObjUserHeadPortrait(userInfo1.getHeadPortrait());
                            }
                            UserInfo userInfo2 = this.userInfoMapper.selectByPrimaryKey(pk.getToUserId());
                            if (userInfo2 != null && userInfo2.getHeadPortrait() != null) {
                                pk.setToUserHeadPortrait(userInfo2.getHeadPortrait());
                            }
                        } else {
                            Map<String, Object> map = new HashMap<>();
                            map.put("deptId", pk.getObjUserId());
                            map.put("type", pk.getObjUserType());
                            UserInfo objUserInfo = this.userInfoMapper.selectUserInfoByDeptIdAndType(map);
                            map.put("deptId", pk.getToUserId());
                            map.put("type", pk.getToUserType());
                            UserInfo toUserInfo = this.userInfoMapper.selectUserInfoByDeptIdAndType(map);
                            if (objUserInfo != null && toUserInfo != null) {
                                objId = objUserInfo.getId();
                                toUserId = toUserInfo.getId();
                                if (objUserInfo.getHeadPortrait() != null) {
                                    pk.setObjUserHeadPortrait(objUserInfo.getHeadPortrait());
                                }
                                if (toUserInfo.getHeadPortrait() != null) {
                                    pk.setToUserHeadPortrait(toUserInfo.getHeadPortrait());
                                }
                            }

                        }

                        //如果发起人是我，就修改显示状态
                        if ((objId.equals(userInfo.getId()) || objId.equals(userInfo.getDeptId())) && pk.getIsReceive() == 2) {
                            pk.setIsReceive(0);
                        }
                        //倒计时
                        if (pk.getState() == 2) { // 进行中的
                            String datePoor = getDatePoor(pk.getEndTime(), new Date(), 0L);
                            pk.setDistanceEndTime(datePoor);
                            if(new Date().compareTo(pk.getEndTime())>0)//如果进行中，但是时间过期了，就自动设置为已结束
                            {
                                pk.setState(3);
                                this.pkMapper.updateByPrimaryKeySelective(pk);
                            }
                            //实时的结果
                            //pk.setObjUserPerformance(this.pkResult(pk, objId));
                            //pk.setToUserPerformance(this.pkResult(pk, toUserId));
                        }
                        //匿名
                        if (pk.getIsAnonymous() == 1 && (!objId.equals(userInfo.getId()) || !objId.equals(userInfo.getDeptId()))) {
                            pk.setObjUserName("神秘人");
                            pk.setObjUserId("***");
                        }
                        list.set(i, pk);
                    }

               /* if (pk.getObjUserId() != null) {
                    if(userInfo.getType() == 6 || userInfo.getType() == 11) {
                        UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(pk.getObjUserId());
                        if (userInfo1 != null && userInfo1.getHeadPortrait() != null) {
                            pk.setObjUserHeadPortrait(userInfo1.getHeadPortrait());
                        }
                    }

                }
                if (pk.getToUserId() != null) {
                    if(userInfo.getType() == 6 || userInfo.getType() == 11) {
                        UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(pk.getToUserId());
                        if (userInfo1 != null && userInfo1.getHeadPortrait() != null) {
                            pk.setToUserHeadPortrait(userInfo1.getHeadPortrait());
                        }
                    }
                }
                //倒计时
                if (pk.getState() == 2) { // 进行中的
                    String datePoor = getDatePoor(pk.getEndTime(), new Date(), 0L);
                    pk.setDistanceEndTime(datePoor);
                    //实时的结果
                    pk.setObjUserPerformance(this.pkResult(pk, pk.getObjUserId()));
                    pk.setToUserPerformance(this.pkResult(pk, pk.getToUserId()));
                }
                //匿名
                if (pk.getIsAnonymous() == 1) {
                    if (userInfo.getSourceSys() != 0) {
                        pk.setObjUserName("神秘人");
                        pk.setObjUserId("***");
                    }
                }
                list.set(i, pk);*/
                }
            }
        }else {
           list = this.pkMapper.selectListByPage(params);
        }
        page.setResults(list);
        return page;
    }

    /**
     * 信息导出excel
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<Pk> listToExcel(Map<String, Object> params) throws Exception {
        BasePage<Pk> page = new BasePage();
        page.setPageNo(1);
        page.setPageSize(999999);
        params.put("page", page);
        return this.pkMapper.selectListByPage(params);
    }

    /**
     * 我的pk列表分页查询列表
     *
     * @param params
     * @param page
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Pk> selectMyPkListByPage(Map<String, Object> params, BasePage<Pk> page, UserInfo userInfo) throws Exception {
        params.put("page", page);
        params.put("isMyPkList",1);//去重
        int state = 0;
        if((Integer)params.get("state") != null){
            state = (int)params.get("state");
        }
        //查询每一上级
        Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
        List<Dept> deptList = new ArrayList<>();
        List<String> deptIdList = new ArrayList<>();
        deptIdList.add(userInfo.getId());
        //每一下级
        this.selectSonId(dept.getCode(),deptIdList);
        //每一上级
        if(dept.getType() != 0){
            this.selectParentDept(dept.getCode(),deptList);
        }
        if(deptList != null && deptList.size() > 0){
            for (Dept dept1 : deptList) {
                deptIdList.add(dept1.getId());
            }
        }
        //根据部门查用户
        List<UserInfo> userInfoList = new ArrayList<>();
        if(userInfo.getSourceSys() == 1){ //主播
            userInfoList = this.userInfoMapper.selectAnchorInfoByDeptIds(deptIdList);
        }else {
            userInfoList = this.userInfoMapper.selectSalesUserInfoByDeptIds(deptIdList);
        }
        if(userInfoList != null && userInfoList.size() >0){
            for (UserInfo info : userInfoList) {
                deptIdList.add(info.getId());
            }
        }
        if(state == 5){ //向我发起的pk
            params.put("state",1);
            params.put("toUserType",userInfo.getType());//层级
        }else {
            params.put("objUserIdList",this.removeDuplicate(deptIdList));
        }
        params.put("toUserIdList",this.removeDuplicate(deptIdList));
        List<Pk> list = this.pkMapper.selectListByPage(params);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Pk pk = list.get(i);
                Integer type = pk.getObjUserType();
                String objId = "";
                String toUserId = "";
                if (pk.getObjUserId() != null && pk.getToUserId() != null) {
                    if (type == 6 || type == 11) {
                        objId = pk.getObjUserId();
                        toUserId = pk.getToUserId();
                        UserInfo userInfo1 = this.userInfoMapper.selectByPrimaryKey(pk.getObjUserId());
                        if (userInfo1 != null && userInfo1.getHeadPortrait() != null) {
                            pk.setObjUserHeadPortrait(userInfo1.getHeadPortrait());
                        }
                        UserInfo userInfo2 = this.userInfoMapper.selectByPrimaryKey(pk.getToUserId());
                        if (userInfo2 != null && userInfo2.getHeadPortrait() != null) {
                            pk.setToUserHeadPortrait(userInfo2.getHeadPortrait());
                        }
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        map.put("deptId", pk.getObjUserId());
                        map.put("type", pk.getObjUserType());
                        UserInfo objUserInfo = this.userInfoMapper.selectUserInfoByDeptIdAndType(map);
                        map.put("deptId", pk.getToUserId());
                        map.put("type", pk.getToUserType());
                        UserInfo toUserInfo = this.userInfoMapper.selectUserInfoByDeptIdAndType(map);
                        if (objUserInfo != null && toUserInfo != null) {
                            objId = objUserInfo.getId();
                            toUserId = toUserInfo.getId();
                            if (objUserInfo.getHeadPortrait() != null) {
                                pk.setObjUserHeadPortrait(objUserInfo.getHeadPortrait());
                            }
                            if (toUserInfo.getHeadPortrait() != null) {
                                pk.setToUserHeadPortrait(toUserInfo.getHeadPortrait());
                            }
                        }

                    }

                    //如果发起人是我，就修改显示状态
                    if ((objId.equals(userInfo.getId()) || objId.equals(userInfo.getDeptId())) && pk.getIsReceive() == 2) {
                        pk.setIsReceive(0);
                    }
                    //倒计时
                    if (pk.getState() == 2) { // 进行中的
                        String datePoor = getDatePoor(pk.getEndTime(), new Date(), 0L);
                        pk.setDistanceEndTime(datePoor);
                        if(new Date().compareTo(pk.getEndTime())>0)//如果进行中，但是时间过期了，就自动设置为已结束
                        {
                            pk.setState(3);
                            Integer objUserHeadPortait=pk.getObjUserHeadPortrait()==null?0:Integer.parseInt(pk.getObjUserHeadPortrait());
                            Integer toUserHeadPortait=pk.getToUserPerformance()==null?0:Integer.parseInt(pk.getToUserPerformance());
                            if(objUserHeadPortait==toUserHeadPortait)
                            {
                                pk.setResult(3);
                            }
                            else if(objUserHeadPortait>toUserHeadPortait)
                            {
                                pk.setResult(2);
                            }
                            else
                            {
                                pk.setResult(1);
                            }
                            this.pkMapper.updateByPrimaryKeySelective(pk);
                        }
                        //实时的结果
                        //pk.setObjUserPerformance(this.pkResult(pk, objId));
                        //pk.setToUserPerformance(this.pkResult(pk, toUserId));
                    }
                    //匿名
                    if (pk.getIsAnonymous() == 1 && (!objId.equals(userInfo.getId()) || !objId.equals(userInfo.getDeptId()))) {
                        pk.setObjUserName("神秘人");
                        pk.setObjUserId("***");
                    }
                    if(userInfo.getType() == pk.getToUserType()){ //是否显示接受按钮
                        pk.setIsView(1);
                    }else {
                        pk.setIsView(0);
                    }
                    list.set(i, pk);
                }
            }
        }
        page.setResults(list);
        return page;
    }

    /**
     * 定时任务评pk胜负
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<Pk> selectPkResultList(Map<String, Object> params, String tenantCode) throws Exception {
        if (StringUtils.isNotEmpty(tenantCode)) {
            TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
        }
        return this.selectPkResultList(params);
    }

    /**
     * 定时任务评pk胜负
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<Pk> selectPkResultList(Map<String, Object> params) throws Exception {
        return this.pkMapper.selectPkResultList(params);
    }

    /**
     * 统计pk通知数据
     * @param toUserId
     * @return
     * @throws Exception
     */
    @Override
    public Integer countPkNum(String toUserId) throws Exception {
        return this.pkMapper.countPkNum(toUserId);
    }

    /**
     * pk结果
     *
     * @param pk
     * @return
     */
    private String pkResult(Pk pk, String userId) throws Exception {
        String result = "";
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatTimes = new SimpleDateFormat("yyyy-MM-dd");
        if (pk != null && pk.getType() != null) {
            int type = pk.getType();
            Map<String, Object> map = new HashMap();
            List<String> userList = this.selectUserList(pk,userId);
            if(userList != null && userList.size() > 0){
                map.put("list", userList);
                map.put("startTime", formatTime.format(pk.getBeginTime()));
                map.put("endTime", formatTime.format(new Date()));
                if (type == 1) { //直播直播时长
                    Long objTimes = this.anchorRelateLiveMapper.pkCountAnchorLiveTimeByIds(map);
                    result = this.getDatePoor(new Date(), new Date(), objTimes);
                } else if (type == 2) { //主播人气值
                    Integer userNum = this.playerMapper.pkSelectAnchorVisitsNumber(map);
                    result = userNum.toString();
                } else if (type == 3) { //优质用户数
                    Integer userNum = this.playerMapper.selectHighQualityUserCount(map);
                    result = userNum.toString();
                } else if (type == 4) { //潜力用户数
                    Integer userNum = this.playerMapper.pkSelectPotentialUsersCount(map);
                    result = userNum.toString();
                } else if (type == 5) { //内荐人数
                    Integer countRecommends = this.recruitRelateRecommendMapper.countRecommends(map);
                    result = countRecommends.toString();
                } else if (type == 6) { //主播心动用户
                    Integer userNum = this.playerMapper.pkSelectHeartbeatCount(map);
                    result = userNum.toString();
                } else if (type == 7) { //新用户充值金额
                    map.put("isNewPlayer", 1);
                    BigDecimal amountSum = this.playerMapper.pkSelectNewChargeAmountSum(map);
                    result = amountSum.toString();
                } else if (type == 8) { //用户充值总金额
                    BigDecimal amountSum = this.playerMapper.pkSelectNewChargeAmountSum(map);
                    result = amountSum.toString();
                } else {
                    throw new Exception("PK类型不存在！");
                }
            }else {
                result = "0";
            }

        }
        return result;
    }

    /**
     * 距离结束时间
     *
     * @param endDate
     * @param nowDate
     * @return
     */
    private String getDatePoor(Date endDate, Date nowDate, Long times) {
        String time = "";
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;
        long diff = times;
        // 获得两个时间的毫秒时间差异
        if (times == 0L) {
            diff = endDate.getTime() - nowDate.getTime();
        }
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        long sec = diff % nd % nh % nm / ns;
        if (day > 0) {
            if (hour > 0) {
                if (min > 0) {
                    if (sec > 0) {
                        time = day + "天" + hour + "小时" + min + "分" + sec + "秒";
                    } else {
                        time = day + "天" + hour + "小时" + min + "分";
                    }
                } else {
                    time = day + "天" + hour + "小时";
                }
            } else {
                time = day + "天";
            }
        } else {
            if (hour > 0) {
                if (min > 0) {
                    if (sec > 0) {
                        time = hour + "小时" + min + "分" + sec + "秒";
                    } else {
                        time = hour + "小时" + min + "分";
                    }
                } else {
                    time = hour + "小时";
                }
            } else {
                if (min > 0) {
                    if (sec > 0) {
                        time = min + "分" + sec + "秒";
                    } else {
                        time = min + "分";
                    }
                } else {
                    time = sec + "秒";
                }
            }
        }
        return time;
    }

    /**
     * 查询组织下的部门
     *
     * @param code
     * @param list
     * @throws Exception
     */
    private void selectSonId(String code, List<String> list) throws Exception {
        List<Dept> deptList = this.deptMapper.selectByParentCode(code);
        if (deptList.size() == 0) {
            Dept dept = this.deptMapper.selectByCode(code);
            list.add(dept.getId());
            return;
        } else {
            for (Dept depts : deptList) {
                list.add(depts.getId());
                selectSonId(depts.getCode(), list);
            }
        }
    }

    /**
     * 删除重复项
     *
     * @param list
     * @return
     */
    private List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    /**
     * 查询用户
     *
     * @return
     */
    private List<String> selectUserList(Pk pk, String userId) throws Exception {
        List<String> list = new ArrayList<>();
        //UserInfo user = this.userInfoMapper.selectByPrimaryKey(userId);
        if(pk != null && pk.getObjUserType() != null) {
            int type = pk.getObjUserType();
            if (type == 6 || type == 11) { // 主播或者业务员
                UserInfo user = this.userInfoMapper.selectByPrimaryKey(userId);
                if(user!=null&&user.getOtherAccount()!=null&&StringUtils.isNotBlank(user.getOtherAccount())) {
                    list.add(user.getOtherAccount());
                }
            } else {
                List<String> deptIdList = new ArrayList<>();
                if (type == 5 || type == 10) { //小组
                    deptIdList.add(userId);
                } else {
                    Dept dept = this.deptMapper.selectByPrimaryKey(userId);
                    if(dept!=null) {
                        this.selectSonId(dept.getCode(), deptIdList);
                    }
                    if (deptIdList != null && deptIdList.size() > 0) {
                        this.removeDuplicate(deptIdList);
                        if (dept.getSourceSys() == 1) {
                            list = this.userInfoMapper.selectAnchorOtherAccountsByDeptIds(deptIdList);
                        } else {
                            list = this.userInfoMapper.selectSalesmanIdsByDeptIds(deptIdList);
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 查询每一上级
     * @param code
     * @param deptList
     * @throws Exception
     */
    private  void selectParentDept(String code ,List<Dept> deptList)throws Exception{
        Dept dept = this.deptMapper.selectByCode(code);
        deptList.add(dept);
        if(dept.getType()==1){
            return;
        }else {
            selectParentDept(dept.getParentCode(),deptList);
        }
    }


}
